package com.ruoyi.web.controller.teacher;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.domain.BasisCaseLoading;
import com.ruoyi.domain.BasisUavTable;
import com.ruoyi.dto.BasisLoadingUavCamp;
import com.ruoyi.service.IBasisCaseLoadingService;
import com.ruoyi.service.IBasisUavService;
import com.ruoyi.service.IBasisUavTableService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 案例加载Controller
 * 
 * @author wangzebing
 * @date 2025-05-11
 */
@RestController
@RequestMapping("/loading")
public class BasisCaseLoadingController extends BaseController
{
    @Autowired
    private IBasisCaseLoadingService basisCaseLoadingService;

    @Value("${snapshot.path}")
    private String snapshotPath;

    @Value("${snapshotKS.path}")
    private String snapshotKSPath;


    @Autowired
    IBasisUavTableService basisUavTableService;

    @Autowired
    IBasisUavService basisUavService;

    /**
     * 查询案例加载列表
     */
    @GetMapping("/list")
    public TableDataInfo list(BasisCaseLoading basisCaseLoading)
    {
        startPage();
        List<BasisCaseLoading> list = basisCaseLoadingService.selectBasisCaseLoadingList(basisCaseLoading);
        return getDataTable(list);
    }

    /**
     * 导出案例加载列表
     */
    @Log(title = "案例加载", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BasisCaseLoading basisCaseLoading)
    {
        List<BasisCaseLoading> list = basisCaseLoadingService.selectBasisCaseLoadingList(basisCaseLoading);
        ExcelUtil<BasisCaseLoading> util = new ExcelUtil<BasisCaseLoading>(BasisCaseLoading.class);
        util.exportExcel(response, list, "案例加载数据");
    }

    /**
     * 获取案例加载详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(basisCaseLoadingService.selectBasisCaseLoadingById(id));
    }

    /**
     * 新增案例加载
     */
    @Log(title = "案例加载", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BasisCaseLoading basisCaseLoading)
    {
        return toAjax(basisCaseLoadingService.insertBasisCaseLoading(basisCaseLoading));
    }

    /**
     * 修改案例加载
     */
    @Log(title = "案例加载", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BasisCaseLoading basisCaseLoading)
    {
        return toAjax(basisCaseLoadingService.updateBasisCaseLoading(basisCaseLoading));
    }

    /**
     * 删除案例加载
     */
    @Log(title = "案例加载", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(basisCaseLoadingService.deleteBasisCaseLoadingByIds(ids));
    }


    @GetMapping("/findPosition")
    public AjaxResult findPosition(String id){
        return success(basisCaseLoadingService.findPosition(id));
    }
    @GetMapping("/findPositionDT")
    public AjaxResult findPositionDT(String id){
        return success(basisCaseLoadingService.findPositionDT(id));
    }


    @GetMapping("/findPositionZH")
    public AjaxResult findPositionZH(String id,Long userId){
        return success(basisCaseLoadingService.findPositionZH(id,userId));
    }


    @GetMapping("/createJsonFile")
    public void createJson(String id){
        BasisCaseLoading position = basisCaseLoadingService.findPosition(id);
//        List<BasisCaseLoading> basisCaseLoadings = Arrays.asList(position);

        Gson gson = new GsonBuilder()
                .setPrettyPrinting() // 格式化输出
                .create();

        // 3. 将List转换为JSON字符串
        String json = gson.toJson(position);

        // 4. 写入文件
        try {
            File file = new File(snapshotPath);
            if (!file.exists()){
                file.mkdirs();
            }

            String filePath = snapshotPath+"\\loading.json";

            Files.write(Paths.get(filePath), json.getBytes());
           // System.out.println("Gson生成JSON文件成功: " + filePath);
        } catch (Exception e) {
            System.err.println("文件写入失败: " + e.getMessage());
        }
    }






    @GetMapping("/createJsonDT")
    public void createJsonDT(String id){
        Map<String, Object> map = new HashMap<>();
        BasisCaseLoading position = basisCaseLoadingService.findPositionDT(id);

        File file = new File(snapshotKSPath);
        if (!file.exists()){
            file.mkdirs();
        }

        map.put("loading",position);

        ObjectMapper objectMapper = new ObjectMapper();

        try {
            objectMapper.writerWithDefaultPrettyPrinter()
                    .writeValue(new File(snapshotKSPath+id+"DT.json"), map);

            System.out.println("JSON文件生成成功！");
        } catch (IOException e) {
            System.err.println("生成JSON文件时出错：" + e.getMessage());
            e.printStackTrace();
        }
    }








    @PostMapping("/createAircraftJsonFile")
    public AjaxResult createAircraftJsonFile(@RequestBody Map<String,Object> map) {
        String aircraftJson = (String) map.get("aircraftJson");
        int idnexcount = (int) map.get("idnexcount");
        String loadingId = (String) map.get("loadingId");



        try {
            ObjectMapper mapper = new ObjectMapper();
            ObjectNode jsonNode = (ObjectNode) mapper.readTree(aircraftJson);
            // 配置缩进（美化输出）
            ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();

            if (idnexcount == 1){
                Map<String, Object> map1 = new HashMap<>();

                ObjectMapper objectMapper = new ObjectMapper();
                BasisCaseLoading position = basisCaseLoadingService.findPosition(loadingId);
                map1.put("loading",position);

                File file = new File(snapshotKSPath);
                if (!file.exists()){
                    file.mkdirs();
                }
                String filePath = snapshotKSPath+loadingId+"Fist.json";

                objectMapper.writerWithDefaultPrettyPrinter()
                        .writeValue(new File(filePath), map1);



//            Files.write(Paths.get(filePath), aircraftJson.getBytes());
//                writer.writeValue(new File(filePath), jsonNode);

               // System.out.println("Gson生成JSON文件成功: " + filePath);
                return success(filePath);
            }else if (idnexcount == 2){

                File file = new File(snapshotKSPath);
                if (!file.exists()){
                    file.mkdirs();
                }

                String filePath = snapshotKSPath+loadingId+"DT.json";

                writer.writeValue(new File(filePath), jsonNode);

               // System.out.println("Gson生成JSON文件成功: " + filePath);

                return success(filePath);
            } else if (idnexcount == 3) {
                return success(snapshotKSPath+loadingId+"DT.json");
            }

        } catch (Exception e) {
            System.err.println("文件写入失败: " + e.getMessage());
        }
        return success("");
    }


    @GetMapping("/copyLoading")
    public AjaxResult copyLoading(String id, String name){

        return success(basisCaseLoadingService.copyLoading(id, name));
    }


    @GetMapping("/configBreakpointTime")
    public AjaxResult configBreakpointTime(String loadingId, String breakpointTime){
        return success(basisCaseLoadingService.configBreakpointTime(loadingId, breakpointTime));
    }



//    public static void main(String[] args) {
//        try {
//            // 1. 读取JSON文件内容
//            String jsonContent = new String(Files.readAllBytes(Paths.get(snapshotPath+"\\"+loadingId+".json")));
//
//            // 2. 创建Gson对象
//            Gson gson = new GsonBuilder().create();
//            BasisCaseLoading basisCaseLoading = gson.fromJson(jsonContent, BasisCaseLoading.class);
//            System.out.println(basisCaseLoading.toString());
//            // 3. 将JSON字符串转换为BasisCaseLoading对象
//        } catch (IOException e) {
//            System.err.println("读取文件失败: " + e.getMessage());
//        } catch (Exception e) {
//            System.err.println("解析JSON失败: " + e.getMessage());
//        }
//
//    }

}
